﻿
using Castle.Core.Internal;
using Coldairarrow.Business.Interface;
using Coldairarrow.Entity.Base_Manage;
using Coldairarrow.Entity.Interface;
using Coldairarrow.Util;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics.Tracing;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Security.Cryptography;
using System.Threading;
using System.Threading.Tasks;
using static Coldairarrow.Business.Interface.AP_PAYBILL_SAVEDTO.Data;

namespace Coldairarrow.Business.Interface
{
    public class WBOrdersInterfaceBusiness : Interface_BaseBusiness, IJob_Business, ITransientDependency
    {
        public List<OL_FilterDTO> Filters;
        public WBOrdersInterfaceBusiness()
        {
            this.InterfaceName = "WB组装订单列表";
            //获取字段的映射关系
            tableField = GetMapField("editRow");
            //索引字段
            Keys = GetKeys("editRow");
            indexFields.Add(Keys.Where(X => X.Type == "K").First().Field);
            //查询过滤条件
            Filters = new List<OL_FilterDTO>();


            //查询执行前的事件
            BeforeQueryEvent += InterfaceBusiness_BeforeQueryEvent;
            //查询执行中的事件
            OnQueryEvent += InterfaceBusiness_OnQueryEvent;
            //执行非查询请求中的事件
            OnNoQueryEvent += InterfaceBusiness_OnNoQueryEvent;

        }

        /// <summary>
        /// 执行非查询请求中时间
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="noQueryEventArgs"></param>
        private void InterfaceBusiness_OnNoQueryEvent(object sender, NoQueryEventArgs noQueryEventArgs)
        {
            //API请求是否成功
            noQueryEventArgs.Success = noQueryEventArgs.Result["success"].ToString().ToBool();
        }

        /// <summary>
        /// 查询执行前的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="queryEventArgs"></param>
        private void InterfaceBusiness_BeforeQueryEvent(object sender, QueryEventArgs queryEventArgs)
        {
            //执行查询前添加过滤条件
            if (queryEventArgs.Page.Filters.IsNullOrEmpty() && !Filters.IsNullOrEmpty())
            {
                queryEventArgs.Page.Filters = Filters;
            }

        }

        /// <summary>
        /// 查询执行中的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="queryEventArgs"></param>
        private void InterfaceBusiness_OnQueryEvent(object sender, QueryEventArgs queryEventArgs)
        {
            //是否查询完成
            if (queryEventArgs.Result["data"]["rows"].ToList().Count == 0)
            {
                queryEventArgs.Page.Complete = true;
            }
            //向总行中添加新的行
            queryEventArgs.Rows.AddRange(queryEventArgs.Result["data"]["rows"].ToList());
            //获取总页数
            queryEventArgs.Page.Total = queryEventArgs.Result["data"]["total"].ToString().ToInt();
            //获取查询成功标志
            queryEventArgs.Success = queryEventArgs.Result["success"].ToString().ToBool();
        }


        /// <summary>
        /// 执行增删改查业务
        /// </summary>
        public async void ExecuteInterface()
        {

            try
            {
                //数据库连接
                ConString = JsonSettingHelper.GetSetting("Database:BaseDb:ConnectionString");
                SqlDb = (SqlServerHelper)DbHelperFactory.GetDbHelper(EFCore.Sharding.DatabaseType.SqlServer, ConString);

                //获取此接口的所有API信息
                this.interfaceOption = SqlDb.GetListBySql<Base_InterfaceOption>(@$"SELECT * FROM  Base_InterfaceOption(NOLOCK) WHERE Name='{InterfaceName}' ");
                Base_InterfaceOption queryOption = this.interfaceOption.Where(o => o.OperateType == "getFilterRows").First();//查询API配置
                Base_InterfaceOption insertOption = this.interfaceOption.Where(o => o.OperateType == "addRow").First();//新增API配置
                Base_InterfaceOption upDateOption = this.interfaceOption.Where(o => o.OperateType == "editRow").First();//更行API配置
                Base_InterfaceOption deleteOption = this.interfaceOption.Where(o => o.OperateType == "deleteRow").First();//删除API配置


                //获取源数据
                WB_OrdersInterfaceBusiness WB_Orders = new WB_OrdersInterfaceBusiness();
                List<WB_OrdersDTO.Orders> sourceData = await WB_Orders.QueryAsync<WB_OrdersDTO.Orders>(WB_Orders.WB_Query, WB_Orders.SqlDb);
                //获取状态
                WB_OrdersStatusInterfaceBusiness WB_OrdersStatus = new WB_OrdersStatusInterfaceBusiness();
                WB_OrdersStatus.orders = sourceData.Select(x => x.id.ToLong()).ToList();
                List<WB_OrdersStatus.Orders> statusList = await WB_OrdersStatus.QueryAsync<WB_OrdersStatus.Orders>(WB_OrdersStatus.WB_Query, WB_OrdersStatus.SqlDb);
                foreach (var item1 in sourceData)
                {
                    if (item1.id == "3860105740")
                    {

                        var SSS = "";
                    }
                    //物流状态
                    var s = statusList.Where(x => x.id == item1.id);
                    item1.status = s.IsNullOrEmpty() ? "" : s.First().wbStatus;
                    //卖家状态
                    item1.supplierStatus = s.IsNullOrEmpty() ? "" : s.First().supplierStatus;
                    //中国时间
                    var date = DateTime.Parse(item1.createdAt);
                    item1.createdAt = date.ToString();

                    //金额
                    item1.price = item1.price.IsNullOrEmpty() ? "0" : (item1.price.ToDouble() / 100).ToString();
                    //转换金额
                    item1.convertedPrice = item1.convertedPrice.IsNullOrEmpty() ? "0" : (item1.convertedPrice.ToDouble() / 100).ToString();

                    if (item1.article.Contains("TIH"))
                    {  //品类
                        item1.PrdType = "电磁炉";

                        //品牌
                        item1.Brand = "Tecasa";
                    }
                    else if (item1.article.Contains("TCH"))
                    {
                        //品类
                        item1.PrdType = "电陶炉";

                        //品牌
                        item1.Brand = "Tecasa";
                    }
                    else if (item1.article.Contains("SPF01"))
                    {
                        //品类
                        item1.PrdType = "热水器";

                        //品牌
                        item1.Brand = "Superflame";
                    }
                    else if (item1.article.Contains("SPF02"))
                    {
                        //品类
                        item1.PrdType = "热水器";

                        //品牌
                        item1.Brand = "Mizudo";
                    }
                    else if (item1.article.Contains("CB."))
                    {
                        //品类
                        item1.PrdType = "壁挂炉";

                        //品牌
                        item1.Brand = "Mizudo";
                    }
                    else
                    {
                        //品类
                        item1.PrdType = "";

                        //品牌
                        item1.Brand = "";

                    }

                    //状态
                    if (item1.status == "waiting" && item1.supplierStatus == "complete")
                    {
                        item1.status_S = "已发货";
                    }
                    else if (item1.status == "waiting" && item1.supplierStatus == "new")
                    {
                        item1.status_S = "新订单";
                    }
                    else if (item1.status == "waiting" && item1.supplierStatus == "confirm")
                    {
                        item1.status_S = "准备发货";
                    }
                    else if (item1.status == "sold" || item1.supplierStatus == "receive")
                    {
                        item1.status_S = "买家已收货";
                    }
                    else if (item1.status == "sorted")
                    {
                        item1.status_S = "已分类";
                    }
                    else if (item1.status == "canceled")
                    {
                        item1.status_S = "已取消";
                    }
                    else if (item1.status == "canceled_by_client" || item1.supplierStatus == "reject")
                    {
                        item1.status_S = "买家退货";
                    }
                    else if (item1.status == "declined_by_client" || item1.supplierStatus == "cancel")
                    {
                        item1.status_S = "买家取消";
                    }
                    else if (item1.status == "defect")
                    {
                        item1.status_S = "发现缺陷";
                    }
                    else if (item1.status == "ready_for_pickup")
                    {
                        item1.status_S = "待取货";
                    }
                    else if (item1.status == "postponed_delivery")
                    {
                        item1.status_S = "买家推迟收货";
                    }
                    else
                    {
                        item1.status_S = item1.status;
                    }




                }


                //获取目标数据
                List<WB_OrdersDTO.Orders> targetData = new List<WB_OrdersDTO.Orders>();//目标据集合
                var fDate = sourceData.OrderBy(x => x.createdAt.ToDateTime()).First().createdAt.ToDateTime().ToString("yyyy-MM-dd");
                Filters.Clear();
                Filters.Add(
                //13:>,14>=15:<,16<=
                new OL_FilterDTO() { ControlId = "68c373e96441945281fce584", DataType = 2, SpliceType = 1, FilterType = 14, Value = fDate }//查询条件
            );
                targetData = await QueryAsync<WB_OrdersDTO.Orders>(queryOption, tableField, SqlDb);

                //判断发货获取发货日期

                foreach (var item2 in sourceData)
                {
                    //获取旧的记录
                    var item = targetData.Where(x => x.id == item2.id);
                    //如果有旧的记录，判断状态是否为已发货，已发货记录当前时间为发货时间
                    if (!item.IsNullOrEmpty() && item.Count() > 0)
                    {
                        var first = item.First();
                        if (!first.shipmentDate.IsNullOrEmpty())
                        {
                            item2.shipmentDate = first.shipmentDate;
                        }
                        else if (item2.status_S != "新订单" && item2.status_S != "准备发货" && item2.status_S != "已取消" && item2.status_S != "买家取消")
                        {
                            item2.shipmentDate = DateTime.Now.ToString();
                        }
                    }
                    else//如果没有旧的记录，代表此次为新数据，直接根据状态获取发货时间
                    {

                        if (item2.status_S != "新订单" && item2.status_S != "准备发货" && item2.status_S != "已取消" && item2.status_S != "买家取消")
                        {
                            item2.shipmentDate = item2.createdAt;
                        }

                    }

                }





                if (this.State > 0 && sourceData.Count > 0 )
                {
                    //更新
                    //#region
                    List<WB_OrdersDTO.Orders> updataItem = sourceData.Intersect(targetData, new ComparerFromKeys<WB_OrdersDTO.Orders>(Keys, "RowId")).ToList();//获取交集(更新项)
                    List<OL_RowDTO> updataData = ConvertOL_Row(updataItem, tableField);//需要更新的数据集合
                    ExecuteNoQuery<OL_RowDTO>(updataData, upDateOption, SqlDb);//执行更新
                    //#endregion

                    //新增
                    #region
                    List<WB_OrdersDTO.Orders> insertItem = sourceData.Except(targetData, new ComparerFromKey<WB_OrdersDTO.Orders>(indexFields.First(), "RowId")).ToList();//获取源数据对目标数据的差集(新增项)
                    List<OL_RowDTO> insertData = ConvertOL_Row(insertItem, tableField);//需要新增的数据集合
                    ExecuteNoQuery<OL_RowDTO>(insertData, insertOption, SqlDb);//执行插入行
                    #endregion

                    //删除
                    #region
                    //List<WB_OrdersDTO.Orders> deleteItem = targetData.Except(sourceData, new ComparerFromKey<WB_OrdersDTO.Orders>(indexFields.First(), "RowId")).ToList();//获取目标数对据源数据的差集(删除项)
                    //List<OL_RowDTO> deleteData = ConvertOL_Row(deleteItem, tableField);//需要删除的数据集合
                    //ExecuteNoQuery<OL_RowDTO>(deleteData, deleteOption, SqlDb);//执行删除行

                    List<WB_OrdersDTO.Orders> deleteItem = targetData.Except(sourceData, new ComparerFromKey<WB_OrdersDTO.Orders>(indexFields.First(), "RowId")).ToList();//获取目标数对据源数据的差集(删除项)
                    List<WB_OrdersDTO.Orders> repeatItem = targetData.GroupBy(x => x.GetPropertyValue(indexFields.First())).Where(x => x.Count() > 1).Select(x => x.FirstOrDefault()).ToList();
                    //将重复的项也一起加入删除的列表
                    deleteItem.AddRange(repeatItem);
                    //筛选出删除列表中重复的项
                    var temp = deleteItem.GroupBy(x => x.GetPropertyValue(indexFields.First())).Where(x => x.Count() > 1).Select(x => x.FirstOrDefault()).ToList();
                    deleteItem.AddRange(temp);

                    List<OL_RowDTO> deleteData = ConvertOL_Row(deleteItem, tableField);//需要删除的数据集合
                    ExecuteNoQuery<OL_RowDTO>(deleteData, deleteOption, SqlDb);//执行删除行

                    #endregion

                    //同步数据库
                    SqlDBInterfaceBusiness sqlDBInterface = new SqlDBInterfaceBusiness(Keys);
                    sqlDBInterface.ExecuteInterface<WB_OrdersDTO.Orders>(sourceData, "SD_WB_Orders", $@"WHERE CONVERT(datetime,[createdAt]) >='{fDate}'");

                }
                else
                {
                    throw new NotImplementedException("目标/源查询无数据无法执行接口!!");

                }
            }
            catch (Exception ex)
            {
                AddLog(SqlDb, ex.Message, InterfaceName, "erro", "");
            }
        }

        /// <summary>
        /// 将源数据根据字典映射关系转换成OL_RowDTO
        /// </summary>
        /// <typeparam name="T">源数据</typeparam>
        /// <param name="sourceData">源数据</param>
        /// <param name="map">Key为目标字段名称，Value为源字段名称</param>
        /// <returns></returns>
        public List<OL_RowDTO> ConvertOL_Row<T>(List<T> sourceData, Dictionary<string, string> map)
        {
            List<OL_RowDTO> list = new List<OL_RowDTO>();
            object rowId;
            foreach (var item in sourceData)
            {
                rowId = item.GetPropertyValue("RowId");
                //需要新增的数据
                OL_RowDTO row = new OL_RowDTO() { RowId = rowId.IsNullOrEmpty() ? null : rowId.ToString(), Controls = new List<Control>() };
                foreach (var c in map)
                {
                    //判断对象的字段是否存在
                    if (item.ContainsProperty(c.Value))
                    {
                        //存在则添加数据
                        row.Controls.Add(new Control() { ControlId = c.Key, Value = item.GetPropertyValue(c.Value) });
                    }
                }
                list.Add(row);
            }
            return list;
        }

        /// <summary>
        /// 任务
        /// </summary>
        public void Job()
        {
            ExecuteInterface();
        }
    }

}
